package com.smartleanx.module.hrm.service.examine.examineTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.fastjson2.JSONArray;
import com.smartleanx.framework.datapermission.core.annotation.DataPermission;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.smartleanx.framework.common.pojo.PageParam;
import com.smartleanx.framework.common.pojo.PageResult;
import com.smartleanx.framework.security.core.util.SecurityFrameworkUtils;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.dal.dataobject.examine.examineTemplate.ExamineTemplateDO;
import com.smartleanx.module.hrm.dal.mysql.employee.EmployeeMapper;
import com.smartleanx.module.hrm.dal.mysql.examine.examineTemplate.ExamineTemplateMapper;

@Service
@Validated
public class ExamineTemplateServiceImpl implements ExamineTemplateService {

    @Resource
    private ExamineTemplateMapper examineTemplateMapper;
    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    @DataPermission(enable = false)
    public PageResult<ExamineTemplateDO> getExaminePlanTemplateList(Integer pageNum, Integer pageSize,
                                                                    String templateName) {
        PageParam param = new PageParam();
        param.setPageNo(pageNum);
        param.setPageSize(pageSize);
        PageResult<ExamineTemplateDO> result =
                examineTemplateMapper.selectPage(param, new LambdaQueryWrapper<ExamineTemplateDO>() {
                    {
                        eq(ExamineTemplateDO::getTemplateType, 1);
                        like(StringUtils.isNotBlank(templateName), ExamineTemplateDO::getTemplateName, templateName);
                        orderByDesc(ExamineTemplateDO::getCreateTime);
                    }
                });
        result.getList().forEach(item -> {
            EmployeeDO employeeDO = employeeMapper.selectByUserId(item.getCreateBy());
            if (ObjectUtils.isEmpty(employeeDO)) {
                item.setCreateByName("管理员");
            } else {
                item.setCreateByName(employeeDO.getName());
            }
        });
        return result;
    }

    @Override
    public Integer createPlanTemplate(JSONObject param) {

        // 模板名称
        String templateName = param.getString("templateName");
        // 模板描述
        String description = param.getString("description");
        // 总分
        Integer totalScore = param.getInteger("examineLimit");
        // 模板内容
        String templateJson = param.toJSONString();

        List<JSONObject> wdList = param.getList("examineDimensions", JSONObject.class);
        wdList = JSONObject.parseObject(JSONObject.toJSONString(wdList), new ArrayList<JSONObject>().getClass());
        int wdNum = wdList != null ? wdList.size() : 0;
        int zbNum = 0;
        for (JSONObject wd : wdList) {
            List<JSONObject> zbList = wd.getList("examineDimensionIndexs", JSONObject.class);
            int zbItemNum = zbList != null ? zbList.size() : 0;
            zbNum += zbItemNum;
        }

        ExamineTemplateDO examineTemplateDO = new ExamineTemplateDO();
        examineTemplateDO.setTemplateType(1);
        examineTemplateDO.setTemplateName(templateName);
        examineTemplateDO.setTemplateJson(templateJson);
        examineTemplateDO.setDescription(description);
        examineTemplateDO.setWdNum(wdNum);
        examineTemplateDO.setZbNum(zbNum);
        examineTemplateDO.setTotalScore(totalScore);
        examineTemplateDO.setCreateBy(SecurityFrameworkUtils.getLoginUserId());
        examineTemplateMapper.insert(examineTemplateDO);
        return 1;
    }

    @Override
    public JSONObject getPlanTemplateUpdateInfo(Integer id) {
        ExamineTemplateDO examineTemplateDO = examineTemplateMapper.selectById(id);
        String jsonString = examineTemplateDO.getTemplateJson();
        JSONObject result = JSON.parseObject(jsonString);
        List<JSONObject> examineDimensions = result.getList("examineDimensions", JSONObject.class);
        examineDimensions.forEach(examineDimension -> {
            examineDimension.put("uuId", UUID.randomUUID().toString().replace("-", ""));
        });
        result.put("id", examineTemplateDO.getId());

        return result;
    }

    @Override
    public Integer updatePlanTemplate(JSONObject param) {

        // 模板ID
        Integer id = param.getInteger("id");
        // 模板名称
        String templateName = param.getString("templateName");
        // 模板描述
        String description = param.getString("description");
        // 总分
        Integer totalScore = param.getInteger("examineLimit");
        // 模板内容
        String templateJson = param.toJSONString();

        List<JSONObject> wdList = param.getList("examineDimensions", JSONObject.class);
        wdList = JSONObject.parseObject(JSONObject.toJSONString(wdList), new ArrayList<JSONObject>().getClass());
        int wdNum = wdList != null ? wdList.size() : 0;
        int zbNum = 0;
        for (JSONObject wd : wdList) {
            List<JSONObject> zbList = wd.getList("examineDimensionIndexs", JSONObject.class);
            int zbItemNum = zbList != null ? zbList.size() : 0;
            zbNum += zbItemNum;
        }
        final int zbNumberFinal = zbNum;

        examineTemplateMapper.update(new LambdaUpdateWrapper<ExamineTemplateDO>() {
            {
                eq(ExamineTemplateDO::getId, id);
                set(ExamineTemplateDO::getTemplateName, templateName);
                set(ExamineTemplateDO::getTemplateJson, templateJson);
                set(ExamineTemplateDO::getDescription, description);
                set(ExamineTemplateDO::getWdNum, wdNum);
                set(ExamineTemplateDO::getZbNum, zbNumberFinal);
                set(ExamineTemplateDO::getTotalScore, totalScore);
            }
        });

        return 1;
    }

    @Override
    public Integer deletePlanTemplate(Integer id) {
        examineTemplateMapper.deleteById(id);
        return 1;
    }

    @Override
    @DataPermission(enable = false)
    public PageResult<ExamineTemplateDO> getExamineResultTemplateList(Integer pageNum, Integer pageSize,
                                                                      String templateName) {
        PageParam param = new PageParam();
        param.setPageNo(pageNum);
        param.setPageSize(pageSize);
        PageResult<ExamineTemplateDO> result =
                examineTemplateMapper.selectPage(param, new LambdaQueryWrapper<ExamineTemplateDO>() {
                    {
                        eq(ExamineTemplateDO::getTemplateType, 2);
                        like(StringUtils.isNotBlank(templateName), ExamineTemplateDO::getTemplateName, templateName);
                        orderByDesc(ExamineTemplateDO::getCreateTime);
                    }
                });
        result.getList().forEach(item -> {
            EmployeeDO employeeDO = employeeMapper.selectByUserId(item.getCreateBy());
            item.setCreateByName(employeeDO.getName());
        });
        return result;
    }

    @Override
    public Integer createResultTemplate(JSONObject param) {

        // 模板名称
        String templateName = param.getString("templateName");
        // 模板内容
        String templateJson = param.toJSONString();

        List<JSONObject> resultConfigs = param.getList("resultConfigs", JSONObject.class);
        resultConfigs =
                JSONObject.parseObject(JSONObject.toJSONString(resultConfigs), new ArrayList<JSONObject>().getClass());
        String grade = resultConfigs.stream().map(item -> item.getString("gradeName")).collect(Collectors.joining(","));

        ExamineTemplateDO examineTemplateDO = new ExamineTemplateDO();
        examineTemplateDO.setTemplateType(2);
        examineTemplateDO.setTemplateName(templateName);
        examineTemplateDO.setTemplateJson(templateJson);
        examineTemplateDO.setGrade(grade);
        examineTemplateDO.setCreateBy(SecurityFrameworkUtils.getLoginUserId());
        examineTemplateMapper.insert(examineTemplateDO);
        return 1;
    }

    @Override
    public JSONObject getResultTemplateUpdateInfo(Integer id) {
        ExamineTemplateDO examineTemplateDO = examineTemplateMapper.selectById(id);
        String jsonString = examineTemplateDO.getTemplateJson();

        JSONObject result = JSON.parseObject(jsonString);
        result.put("id", examineTemplateDO.getId());

        return result;
    }

    @Override
    public Integer updateResultTemplate(JSONObject param) {

        // 模板ID
        Integer id = param.getInteger("id");
        // 模板名称
        String templateName = param.getString("templateName");
        // 模板内容
        String templateJson = param.toJSONString();

        List<JSONObject> resultConfigs = param.getList("resultConfigs", JSONObject.class);
        resultConfigs =
                JSONObject.parseObject(JSONObject.toJSONString(resultConfigs), new ArrayList<JSONObject>().getClass());
        String grade = resultConfigs.stream().map(item -> item.getString("gradeName")).collect(Collectors.joining(","));

        examineTemplateMapper.update(new LambdaUpdateWrapper<ExamineTemplateDO>() {
            {
                eq(ExamineTemplateDO::getId, id);
                set(ExamineTemplateDO::getTemplateName, templateName);
                set(ExamineTemplateDO::getTemplateJson, templateJson);
                set(ExamineTemplateDO::getGrade, grade);
            }
        });
        return 1;
    }

    @Override
    public Integer deleteResultTemplate(Integer id) {
        examineTemplateMapper.deleteById(id);
        return 1;
    }

    @Override
    public List<JSONObject> getResultTemplateSelectList() {

        List<ExamineTemplateDO> list = examineTemplateMapper.selectList(new LambdaQueryWrapper<ExamineTemplateDO>() {
            {
                eq(ExamineTemplateDO::getTemplateType, 2);
            }
        });
        List<JSONObject> result = new ArrayList<>();
        for (ExamineTemplateDO template : list) {
            JSONObject resultItem = JSON.parseObject(template.getTemplateJson());
            resultItem.put("id", template.getId());
            result.add(resultItem);
        }
        return result;
    }
}
